<?php

namespace app\admin\service;

use app\admin\dao\TradeDao;
use app\admin\model\UM as UM;
use app\common\job\TradeRefund;
use app\common\model\Trade;
use app\index\traits\PaymentTrait;
use ShidianUtil\Exception\DataNotExistException;
use think\exception\ValidateException;
use think\facade\Queue;

/**
 * Class OrderRefundService
 * @package app\admin\service
 */
class OrderRefundService
{
    use PaymentTrait;

    // dao
    private TradeDao $tradeDao;

    public function __construct(TradeDao $tradeDao)
    {
        $this->tradeDao = $tradeDao;
    }

    /**
     * 退款审核
     * @param UM $user
     * @param int $id
     * @param array $params
     */
    public function modify(UM $user, int $id, array $params): void
    {
        $params['refundCheckStatus'] ??= Trade::REJECTED;
        params_enums($params, 'refundCheckStatus', Trade::REJECTED, Trade::AGREED);

        $record = Trade::field(true)->where('id', $id)->find();

        if (is_null($record)) {
            throw new DataNotExistException('该订单不存在或已被删除');
        }

        // 支付状态
        if ($record->payStatus != Trade::PAID) {
            throw new ValidateException('该订单未支付');
        }

        // 退款状态
        if ($record->refundStatus != Trade::REFUNDING) {
            throw new ValidateException('该订单不在退款中，无法审核');
        }

        // 退款审核状态
        if ($record->refundCheckStatus != Trade::UNCHECKED) {
            throw new ValidateException('该订单已审核，请勿重复操作');
        }

        // 结算状态
        if ($record->settleStatus == Trade::SETTLING || $record->settleStatus == Trade::SETTLED) {
            throw new ValidateException('该订单已结算，不能退款');
        }

        $record->refundCheckStatus = $params['refundCheckStatus'];
        if($params['refundCheckStatus'] == Trade::AGREED){
            // 同意
            $record->refundResult = Trade::UNSTART;
        }
        if($params['refundCheckStatus'] == Trade::REJECTED){
            // 拒绝
            $record->refundStatus = Trade::REFUND_FAILED;
        }
        $record->refundCheckUserId = $user->id;
        $record->save();

        // 通过审核
        if ($record->refundCheckStatus == Trade::AGREED) {

            // 触发退款成功事件
            event('RefundSuccess', $record);

            // 添加退款任务
            $job_data = ['id' => $record->id];
            Queue::push(TradeRefund::class, $job_data);
        }

    }

}
